/**
  对默认的router对象扩展两个方法：show、return，以实现临近两个View之间触发式的消息传递并实现路由的切换
*/
export default {
  init(router) {
    var routerCallbacks = {}

    /**
     * 显示指定路由并传递参数对象，可指定关闭的回调函数和任意回调函数
     * @param {Object} param
     * @param {Function} onreturn
     * @param {Function} callback
     */
    router.show = (param, onreturn, callback, thisObj) => {
      thisObj = thisObj != null ? thisObj : callback && !callback.IsFunction ? callback : onreturn && !onreturn.IsFunction ? onreturn : null
      onreturn = param.onreturn || onreturn
      if (onreturn && !onreturn.IsFunction) {
        onreturn = null
      }
      callback = param.callback || callback
      if (callback && !callback.IsFunction) {
        callback = null
      }
      if (onreturn || callback) {
        routerCallbacks[param.path || param.name] = {
          return: onreturn,
          callback: callback,
          $this: thisObj
        }
      }
      delete param.onreturn
      delete param.callback
      window.trackEvent('页面', '显示', param.name || param.path, 1)
      router.push(param)
    }

    /**
     * 切换到子路由
     * @param {any} param
     * @param {any} onreturn
     * @param {any} callback
     * @param {any} thisObj
     */
    router.showChild = (param, onreturn, callback, thisObj) => {
      if (router.currentRoute.name) {
        param.name = router.currentRoute.name + '.' + param.name
      } else {
        param.name = param.name
      }
      router.show(param, onreturn, callback, thisObj)
    }

    /**
     * 弹出一个新的WebView来显示指定路由的页面
     * @param {any} param
     * @param {any} onreturn
     * @param {any} callback
     * @param {any} thisObj
     */
    router.openView = (param, onreturn, callback, thisObj) => {
    }

    /**
     * 返回上一个路由并返回参数
     * @param {Object} param
     */
    router.return = param => {
      var route = router.currentRoute
      var path = route.path
      var back = route.params.back || route.query.back || -1
      var callbackObj = routerCallbacks[path] || routerCallbacks[router.currentRoute.name]
      if (callbackObj) {
        //  清除回调函数映射
        var $this = callbackObj.$this
        delete callbackObj.$this
        delete routerCallbacks[path]
        delete routerCallbacks[router.currentRoute.name]
        var backStep = Function.callFun(callbackObj.return, $this, param)
        if (backStep < 0) {
          back = backStep
        }
      }
      router.go(back)
    }

    /**
     * 执行一次回调函数
     * @param {any} param
     */
    router.callback = param => {
      var path = router.currentRoute.path
      var callbackObj = routerCallbacks[path] || routerCallbacks[router.currentRoute.name]
      if (callbackObj) {
        Function.callFun(callbackObj.callback, callbackObj.$this, param)
      }
    }

    /**
     * 清除本次路由的回调函数映射
     */
    router.clearCallback = path => {
      delete routerCallbacks[path || router.currentRoute.path]
      return router
    }
  }
}
